package com.xinyiweidai.xinyiweidai.dialog;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lan.mylibrary.okhttp.OkHttpUtils;
import com.lan.mylibrary.okhttp.callback.FileCallBack;
import com.lan.mylibrary.ui.MyToast;
import com.xinyiweidai.xinyiweidai.R;

import java.io.File;

import okhttp3.Request;


/**
 * class:   DownloadDialog
 * data：   2018/9/5  14:32
 * author:  LanX
 * Description: app下载进度的dialog
 */

public class DownloadDialog extends DialogFragment {


    private File apkFile;
    private TextView tv_progressbar;
    private ProgressBar progressBar;


    public static DownloadDialog newInstance(String packageSize, String url) {
        Bundle args = new Bundle();
        args.putString("url", url);
        args.putString("packageSize", packageSize);
        DownloadDialog fragment = new DownloadDialog();
        fragment.setArguments(args);
        return fragment;
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onStart() {
        super.onStart();
        Window window = this.getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.CENTER;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(params);
        View decorView = window.getDecorView();
        decorView.setPadding(100, 0, 100, 0);
        decorView.setBackground(new ColorDrawable(Color.TRANSPARENT));
        decorView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_UP) {
            }
            return true;
        });
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_download, container, false);
        tv_progressbar = view.findViewById(R.id.tv_progressbar);
        progressBar = view.findViewById(R.id.progressBar);

        tv_progressbar.setText("0%");
        progressBar.setProgress(0);

        checkSDCardPermission();
        return view;
    }


    @SuppressLint("NewApi")
    private void checkSDCardPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            DownloadDialog.this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
        } else {
            loadApk();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1000:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    loadApk();
                } else {
                    DownloadDialog.this.dismiss();
                    MyToast.showError(getActivity(), "您拒绝了请求");
                }
                break;
            case 1002:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    installApk();
                } else {
                    MyToast.showError(getActivity(), "您拒绝了请求");
                }
                break;
            default:
        }
    }


    private void loadApk() {
        OkHttpUtils
                .get()
                .url(getArguments().get("url").toString())
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "aidouhua.apk") {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void inProgress(float progress) {
                        tv_progressbar.setText((int) (100 * progress) + "%");
                        progressBar.setProgress((int) (100 * progress));
                    }

                    @Override
                    public void onError(Request request, Exception e) {
                        MyToast.showError(getActivity(), "网络异常");
                    }

                    @Override
                    public void onResponse(File file) {
                        apkFile=file;
                        checkOreo();
                    }
                });
    }


    private void checkOreo() {
        if (Build.VERSION.SDK_INT >= 26) {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.REQUEST_INSTALL_PACKAGES) != PackageManager.PERMISSION_GRANTED) {
                DownloadDialog.this.requestPermissions(new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 1002);
            } else {
                installApk();
            }
        } else {
            installApk();
        }
    }


    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri apkUri = FileProvider.getUriForFile(getActivity(), "com.xinyiweidai.xinyiweidai.fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }

        DownloadDialog.this.dismiss();
        getActivity().startActivity(intent);
    }

}
